<template>
	<view class="container">
		<unicloud-db ref="udb" v-slot:default="{data, pagination, loading, hasMore, error}" :collection="collectionList"
			field="timestamp,title,desc,url,direction,count,status" :page-size="10" @load="dbLoad" :where="whereStr"
			:orderby="orderStr">
			<view v-if="error">{{error.message}}</view>
			<view v-else-if="data">
				<!-- 悬浮菜单 -->
				<float-bar popupType="left" :shaixuanBtnIsShow="true" :delBtnIsShow="isShowCheck" :tabIsShowValue="100"
					:bagesCount="selectArr.length.toString()" ref="floatBar" @popupChange="popupChange"
					@deleteData="deleteData" :customItem="customItem">
					<template v-slot:default>
						<view class="popup-content">
							<text class="title">筛选</text>
							<uni-section class="mb-10" title="方向" type="line">
								<uni-data-checkbox mode="tag" selectedColor="#32DBBA" v-model="fxCheck"
									:localdata="fxRanges"></uni-data-checkbox>
							</uni-section>
							<uni-section class="mb-10" title="时间排序" type="line">
								<uni-data-checkbox mode="tag" selectedColor="#32DBBA" v-model="timeCheck"
									:localdata="TimeRanges"></uni-data-checkbox>
							</uni-section>
							<uni-section class="mb-10" title="审核状态" type="line">
								<uni-data-checkbox mode="tag" selectedColor="#32DBBA" v-model="stCheck"
									:localdata="statusRanges"></uni-data-checkbox>
							</uni-section>
							<uni-section class="mb-10" title="描述搜索" type="line">
								<uni-search-bar v-model.trim="searchValue" ref="searchRef" placeholder="搜索"
									cancelButton="none"></uni-search-bar>
							</uni-section>
							<uni-section class="mb-10" title="">
								<button class="uni-button" @click="clickOk">确定</button>
							</uni-section>
						</view>
					</template>
				</float-bar>
				<!-- 全选组件 -->
				<view v-if="isShowCheck">
					<check-all :allCheck="isCheckAll" @cancelClick="cancelClick" @checkChange="checkChange"></check-all>
				</view>
				<uni-list>
					<uni-swipe-action ref="swipe">
						<uni-swipe-action-item v-for="item in data" :key="item._id" autoClose
							:right-options="[{text: '删除',style: {backgroundColor: '#dd524d'}}]"
							@click="(e)=>{clickSwipeItem(e,item)}"
							@longpress="(target,timestamp)=>{longPress(target,timestamp,item)}">
							<uni-list-item :showArrow="!isShowCheck" :title="item.desc" :clickable="true"
								@click="handleItemClick(item._id)">
								<template v-if="isShowCheck" v-slot:header>
									<checkbox @click="checkboxChange(item)" value="cb" :checked="item?.isCheck"
										color="#fff" activeBackgroundColor="#32DBBA"
										style="transform:scale(0.7);margin-left: -20rpx;" />
								</template>
								<template v-slot:body>
									<text class="descBox">
										{{item.desc}}
									</text>
								</template>
								<template v-slot:footer>
									<view class="timeBox">
										<view class="tagbox">
											<uni-tag class="tag" inverted :text="item.direction == 0 ? '横屏' : '竖屏'"
												:type="item.direction == 0 ? 'warning' : 'primary'" size="mini" />
											<uni-tag class="tag rightTag" :text="statusMap[item.status].text"
												size="mini"
												:custom-style="`background-color:${statusMap[item.status].color};border-color:${statusMap[item.status].color};`" />
										</view>
										<uni-dateformat class="time" format="yyyy/MM/dd"
											:date="item.timestamp"></uni-dateformat>
										<uni-dateformat class="time" format="hh:mm:ss"
											:date="item.timestamp"></uni-dateformat>
									</view>
								</template>
							</uni-list-item>
						</uni-swipe-action-item>
					</uni-swipe-action>
				</uni-list>
			</view>
			<uni-load-more :status="loading?'loading':(hasMore ? 'more' : 'noMore')"></uni-load-more>
		</unicloud-db>
		<!-- <uni-fab ref="fab" horizontal="right" vertical="bottom" :pop-menu="false" @fabClick="fabClick" /> -->
	</view>
</template>

<script>
	import {
		store,
		mutations
	} from '@/uni_modules/uni-id-pages/common/store.js'

	// 基于 schema2code 生成的代码修改
	const whereStr = `user_id == '${store.userInfo._id}' && status != 4`
	export default {
		data() {
			return {
				statusMap: [{
						"value": 0,
						"text": '未审核',
						"color": '#FF9800'
					},
					{
						"value": 1,
						"text": '可用',
						"color": '#4CAF50'
					},
					{
						"value": 2,
						"text": '停用',
						"color": '#9E9E9E'
					},
					{
						"value": 3,
						"text": '驳回',
						"color": '#F44336'
					},
					{
						"value": 4,
						"text": '删除',
						"color": '#F44336'
					}
				],
				customItem: [{
					callback: () => {
						this.fabClick()
					},
					type: 'plusempty',
					status: true
				}],
				searchValue: '',
				orderStr: "timestamp desc",
				whereStr: whereStr,
				isClickOk: false,
				timeCheck: [1],
				fxCheck: [2],
				stCheck: [-1],
				statusRanges: [{
					"value": -1,
					"text": "全部"
				}, {
					"value": 0,
					"text": "未审核"
				}, {
					"value": 1,
					"text": "已发布"
				}, {
					"value": 3,
					"text": "被驳回"
				}],
				TimeRanges: [{
					"value": 0,
					"text": "顺序"
				}, {
					"value": 1,
					"text": "倒序"
				}],
				fxRanges: [{
					"value": 2,
					"text": "全部"
				}, {
					"value": 0,
					"text": "横屏"
				}, {
					"value": 1,
					"text": "竖屏"
				}],
				selectArr: [],
				preventClick: false,
				isShowCheck: false,
				collectionList: "wallpaper-userShare",
				loadMore: {
					contentdown: '',
					contentrefresh: '',
					contentnomore: ''
				}
			}
		},
		onPullDownRefresh() {
			this.$refs.udb.loadData({
				clear: true
			}, () => {
				uni.stopPullDownRefresh()
			})
		},
		onReachBottom() {
			this.$refs.udb.loadMore()
		},
		computed: {
			isCheckAll: {
				get() {
					return this.$refs.udb?.dataList.every(item => item.isCheck)
				},
				set(val) {
					this.$refs.udb?.dataList.forEach(item => item.isCheck = val)
				}
			}

		},
		methods: {
			clickOk() {
				let wereStr = whereStr
				if (this.fxCheck != 2 && this.fxCheck != undefined) {
					wereStr = wereStr + `&& direction == ${this.fxCheck?.toString()}`

				}
				if (this.stCheck != -1 && this.stCheck != undefined) {
					wereStr = wereStr + `&& status == ${this.stCheck?.toString()}`

				}
				if (this.searchValue != '') {
					wereStr = wereStr + `&& ${new RegExp(this.searchValue, 'i')}.test(desc) `
					// console.log(wereStr);
				}

				let orderStr = "timestamp desc"
				if (this.timeCheck == 0) {
					orderStr = "timestamp asc"
				}

				this.isClickOk = true
				this.whereStr = wereStr
				this.orderStr = orderStr
				this.selectArr = []
				this.$refs.floatBar.popup.close()
			},
			popupChange(e) {
				// console.log(e);
				if (!e.show && !this.isClickOk) {
					this.timeCheck = this.timeC
					this.fxCheck = this.fxC
					this.stCheck = this.stC
					this.searchValue = this.searchValueC
				} else {
					this.isClickOk = false
					this.timeC = this.timeCheck
					this.fxC = this.fxCheck
					this.stC = this.stCheck
					this.searchValueC = this.searchValue
				}
			},
			// 用于二次处理数据
			dbLoad(data, ended, pagination) {
				// `data` 当前查询结果
				// `ended` 是否有更多数据
				// `pagination` 分页信息 HBuilderX 3.1.5+ 支持
			},
			// 全选组件 全选按钮
			checkChange(e) {
				this.isCheckAll = !this.isCheckAll
				this.selectArr = this.$refs.udb?.dataList.filter(item => item.isCheck)
			},
			// 全选组件 取消按钮
			cancelClick() {
				this.preventClick = false
				this.isShowCheck = false
				this.isCheckAll = false
				this.selectArr = []
			},
			// 复选框改变
			checkboxChange(item) {
				item.isCheck = !item.isCheck
				this.selectArr = this.$refs.udb?.dataList.filter(item => item.isCheck)
				// console.log(item)
			},
			// 长按
			longPress(target, timestamp, item) {
				// console.log(target, timestamp, item)
				this.preventClick = true
				this.isShowCheck = true
			},
			// deleteData 真删
			deleteData() {
				// 真删除
				uni.showModal({
					title: '提示',
					content: '确认要删除吗？',
					success: async (e) => {
						if (e.confirm) {
							const res = await Promise.all(this.selectArr.map(item => {
								return this.delFun(item)
							}))
							if(!this.$refs.udb.dataList.length){
								this.cancelClick()
							}
						}
						
					}
				})
				
				
			},
			/* deleteData 状态改为删除
			deleteData(){
				// console.log('deleteData');
				const _idArr = this.selectArr.map(item => item._id)
				// this.$refs.udb.remove(_idArr, {
				// 	confirmContent: '确认要删除吗？',
				// 	needConfirm: true,
				// 	needLoading: true
				// })
				uni.showModal({
					title:'提示',
					content:'确认要删除吗？',
					success: async (e) => {
						if(e.confirm){
							await Promise.all(
							    _idArr.map(item => 
							        this.$refs.udb.update(item, {
							            status: 4
							        }, {
							            needConfirm: false,
							            needLoading: true,
										showToast: false,
										
							        })
							    )
							)
							uni.showToast({
								icon: 'success',
								title: '删除成功'
							})
							this.cancelClick()
							this.selectArr = []
							this.$refs.udb.refresh()
						}
					}
				})
			},
			*/
			
			// 滑块删除单条
			clickSwipeItem(e, item, batch = false) {
				// 批量删除不提示 showModal
				if(batch){
					this.delFun(item)
				}else{
				// 单个删除
					uni.showModal({
						title: '提示',
						content: '确认要删除吗？',
						success: async (e) => {
							if (e.confirm) {
								await this.delFun(item)
							}else{
								this.$refs.swipe.closeAll()	
							}
						}
					})
				}
				
			},
			delFun(item){
				// 真删
				return new Promise((resolve, reject) => {
					this.$refs.udb.remove(item._id, {
						needConfirm: false,
						needLoading: true,
						success() {
							uniCloud.callFunction({
								name: 'my-deleteFiles',
								data: {
									fileList: [item.url] // 替换为你要删除的文件 ID
								},
								success: (res) => {
									// console.log('删除结果:', res.result);
									console.log('删除成功');
									resolve(true)
								},
								fail: (error) => {
									// console.error('删除失败:', error);
									console.log('删除失败');
									resolve(false)
								}
							});
						},
						fail() {
							resolve(false)
						}
					})
				})
				
				
				/* 状态改为删除
				await this.$refs.udb.update(item._id,{
					status: 4
				} ,{
					needConfirm: false,
					needLoading: true,
					showToast: false
				})
				uni.showToast({
					icon: 'success',
					title: '删除成功'
				})
				this.cancelClick()
				this.selectArr = []
				this.$refs.udb.refresh()
				*/
			},
			handleItemClick(id) {
				if (this.preventClick) {
					return
				}
				// 打开修改页面
				uni.navigateTo({
					url: './wallpaperDetail?id=' + id,
					events: {
						// 监听新增数据成功后, 刷新当前页面数据
						refreshData: () => {
							this.$refs.udb.loadData({
								clear: true
							})
						}
					}
				})
			},
			fabClick() {
				// 打开新增页面
				uni.navigateTo({
					url: './wallpaperAdd',
					events: {
						// 监听新增数据成功后, 刷新当前页面数据
						refreshData: () => {
							this.$refs.udb.loadData({
								clear: true
							})
						}
					}
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	// .uni-tag--success{
	// 	background-color: $theme-bg-color2;
	// 	border-color: $theme-bg-color2;
	// }
	// .uni-tag--warning{
	// 	background-color: $theme-bg-color1;
	// 	border-color: $theme-bg-color1;
	// }

	.uni-searchbar {
		padding: 0;
	}

	:deep() {
		.uni-group__title {
			background-color: transparent;
		}

		.uni-section-header__decoration {
			background-color: $theme-bg-color2 !important;
		}

		.uni-section-content {
			padding-left: 25rpx;
			padding-right: 25rpx;
		}

		.uni-button {
			background-color: $theme-bg-color2;
			color: #fff;
			border-radius: 0;
			width: 100%;
		}
	}

	

	.tag {
		margin-bottom: 8rpx;
	}

	.timeBox {

		// width: 180rpx;
		.tagbox {
			// width: 180rpx;
			display: flex;
			justify-content: flex-end;

			.rightTag {
				margin-left: 8rpx;
			}

		}

		font-size: 24rpx;
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		justify-content: center;
	}

	.descBox {
		flex: 1;
		overflow: hidden;
		// 最多显示3行
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 3;
		font-size: 34rpx;
	}

	.popup-content {}

	.popup-content {
		width: 70vw;

		.title {
			font-size: 55rpx;
			display: block;
			margin: 20rpx 0 20rpx 15rpx;
		}

		:deep() {
			.uni-group {
				margin-top: 0 !important;
			}
		}
	}
</style>